#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<stack>

using namespace std;

struct ListNode {
    int val;
    ListNode* next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode* next) : val(x), next(next) {}
};

ListNode* removeNodes(ListNode* head) {
    stack<ListNode*> s;
    ListNode* cur = head;
    while (cur != nullptr)
    {
        while (!s.empty() && s.top()->val < cur->val)
            s.pop();
        s.push(cur);
        cur = cur->next;
    }

    ListNode* prev = nullptr;
    cur = nullptr;
    while (!s.empty())
    {
        cur = s.top();
        cur->next = prev;
        prev = cur;
        s.pop();
    }
    return cur;
}

int main()
{
    ListNode n1(5), n2(2), n3(13), n4(3), n5(8);
    n1.next = &n2, n2.next = &n3, n3.next = &n4, n4.next = &n5;
    removeNodes(&n1);
    return 0;
}